const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const session=require('koa-session')


let list = [
  {
    username: 'qqq',
    password: 'qqq'
  },
  {
    username: 'zhangsan',
    password: 'qqqq'
  },
  {
    username: 'lisi',
    password: 'qqqq'
  }
]


const newdata=[]
 
router.get('/home', async (ctx, next) => {
 
  const cap = svgCaptcha.create({
    size: 4, // 验证码长度
    width:160,
    height:60,
    fontSize: 50,
    ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
    noise: 2, // 干扰线条的数量
    color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
    background: '#eee' // 验证码图片背景颜色
  })
  
  let img = cap.data // 验证码
  let text = cap.text.toLowerCase() // 验证码字符，忽略大小写
 console.log(text);
 newdata[0]=text
  // 设置响应头
  ctx.response.type = 'image/svg+xml';
 
  ctx.body = img;
});







router.get('/login', async (ctx, next) =>{
    let url =ctx.url;
    let request=ctx.request;
    let reqquery = request.query
    console.log(newdata[0]);
    console.log(reqquery);
    console.log(reqquery.ymz);
    ctx.body={
      message:'成功得到了token',
      code:0,
  }
    for(let i = 0; i < list.length; i++) {
      if (list[i]["username"] ==reqquery.username&&list[i]["password"] ==reqquery.password&&newdata[0]==reqquery.ymz) {
        console.log("yes");
        ctx.body={
          message:'成功得到了token',
          code:1,
      }
      }
    }
    console.log( ctx.body.code);
});
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get("/getdata", async(ctx, next) => {
  ctx.body = "recieved data";
})

router.get("/getlist", async(ctx, next) => {
  ctx.body = chapterList;
})

router.post("/del", async(ctx, next) => {
  let id = ctx.request.body.id;
  let index = '';
  for(let i = 0; i < chapterList.length; i++) {
      if(chapterList[i]["chapterId"] == id) {
        index = i;
      }
  }
  chapterList.splice(index, 1);
  ctx.body = "success";
})

router.post("/sub", async(ctx, next) => {
  let chapter = {
    chapterId: Math.random(),
    chapterTitle: ctx.request.body.chapterTitle,
    timer: ctx.request.body.timer
  }
  chapterList.push(chapter);
  ctx.body = "ok";
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
